package com.my.study.common.security;

import cn.hutool.core.net.URLEncoder;
import com.my.study.common.utils.JsonUtils;
import com.my.study.common.utils.JwtTokenUtils;
import com.my.study.common.utils.ReqRespUtils;
import com.my.study.dto.JwtUserDto;
import com.my.study.entity.MyUserEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.RememberMeAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录成功处理器
 * 
 * @author yidujun
 * @date 2022/8/3 15:06
 */
@Slf4j
@Component("customAuthenticationSuccessHandler")
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    URLEncoder urlEncoder = URLEncoder.createDefault();
    
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        JwtUserDto jwtUserDto = JwtTokenUtils.getUserFromAuthentication(authentication);
         if (jwtUserDto == JwtTokenUtils.DEFAULT_USER){
            ReqRespUtils.writeResp(response, "authentication is null or Illegal");
            return;
        }
        log.info("登录成功");
        
        MyUserEntity myUserEntity = jwtUserDto.getMyUserEntity();
        myUserEntity.setPassword(null);
        jwtUserDto.setMyUserEntity(myUserEntity);

        String token = JwtTokenUtils.generateToken(authentication);
        Cookie cookie = new Cookie("token", null);
        cookie.setPath("/");
        cookie.setMaxAge(60 * 60 * 12);
        cookie.setValue(urlEncoder.encode(token, StandardCharsets.UTF_8));
        response.addCookie(cookie);

        Map<String, Object> res = new HashMap<>(4);
        res.put("code", 1);
        res.put("msg", "登录成功");
        res.put("data", jwtUserDto);
        ReqRespUtils.writeResp(response, res);
    }
}
